﻿using System;
using System.Linq;
using Epitech.Krisk.Xna.ScreenManagerLib.ScreenManager;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Epitech.Krisk.Xna.ScreenManagerLib.Widget
{
    public class LineEdit : MenuEntry
    {

        public String Content
        {
            get { return text.Replace("|", ""); }
            set { text = value; }
        }

        public LineEdit() : base("")
        {
        }

        DateTime _lastBackspace = DateTime.Now;
        DateTime _cli = DateTime.Now;

        public override void HandleInput(GameScreen currentScreen, InputState input)
        {
            Keys[] keys = input.GetPressedKeys();
            bool isCliAff = false;

            if (isSelect)
            {
                if (Content.Length > 0 && Content.Last() == '|')
                {
                    Content = Content.Substring(0, Content.Length - 1);
                    isCliAff = true;
                }
                foreach (Keys key in keys)
                {
                    if (key == Keys.Back)
                    {
                        if (Content.Length > 0 && DateTime.Now - _lastBackspace > TimeSpan.FromMilliseconds(100))
                        {
                            Content = Content.Substring(0, Content.Length - 1);
                            _lastBackspace = DateTime.Now;
                        }
                    }
                    else
                    {
                        PlayerIndex tmp;
                        if (input.IsNewKeyPress(key, PlayerIndex.One, out tmp))
                        {
                            switch (key)
                            {
                                case Keys.Space:
                                    Content += " ";
                                    break;
                                default:
                                    if (key.ToString().Length == 1)
                                        Content += key.ToString();
                                    break;
                            }
                        }
                    }
                }
                if (DateTime.Now - _cli > TimeSpan.FromMilliseconds(500))
                {
                    if (!isCliAff)
                        Content += "|";
                    _cli = DateTime.Now;
                }
                else if (isCliAff)
                    Content += "|";
            }
            else
            {
                if (Content.Length > 0 && Content.Last() == '|')
                {
                    Content = Content.Substring(0, Content.Length - 1);
                }
            }
        }
    }
}
